<?php

namespace maotool\util;

use maotool\file\DirUtil;
use maotool\object\StrUtil;

class NpmUtil
{

    public static function run($path, $args = [])
    {
        if (is_file($path)) {
            $dir = DirUtil::dirName($path);
        } else {
            $dir = $path;
        }
        return shell_exec("cd " . $dir . " && npm run " .  StrUtil::join($args, " "));
    }

    public static function ls($path, $args = [])
    {
        return self::lists($path, $args);
    }

    public static function lists($path, $args = [])
    {
        $list = [];
        if (is_file($path)) {
            $dir = DirUtil::dirName($path);
        } else {
            $dir = $path;
        }
        $content = shell_exec("cd " . $dir . " && npm list " .  StrUtil::join($args, " "));
        $lines = preg_split("/\r\n|\n|\r/", $content);
        foreach ($lines as $line) {
            $line = StrUtil::trim($line);
            if (StrUtil::startsWith($line, "+-- ")) {
                $list[] = StrUtil::sub($line, 4, strlen($line));
            } elseif (StrUtil::startsWith($line, "`-- ") && $line != "`-- (empty)") {
                $list[] = StrUtil::sub($line, 4, strlen($line));
            }
        }
        return $list;
    }

    public static function install($path, $args = [])
    {
        $path = PathUtil::path($path);
        if (is_file($path)) {
            $dir = DirUtil::dirName($path);
        } else {
            $dir = $path;
        }
        return shell_exec("cd " . $dir . " && npm install " . StrUtil::join($args, " "));
    }

    public static function uninstall()
    {

    }

    public static function help()
    {

    }

    public static function test()
    {

    }

}